import { EventEmitter } from 'node:events'
import { getLogger } from '../../logger/index'

// 惰性获取 logger，避免在模块加载时初始化
function getLoggerSafe() {
  try {
    return getLogger()
  }
  catch {
    // 如果 logger 未初始化，返回一个简单的 console logger
    return {
      debug: console.log.bind(console),
      info: console.log.bind(console),
      warn: console.warn.bind(console),
      error: console.error.bind(console),
    }
  }
}

/**
 * 任务接口
 */
interface Task {
  id: string
  priority: number
  payload: any
  createdAt: number
  timeout: number
}

/**
 * 任务队列管理器
 *
 * 职责：接收预约任务，维护待执行队列
 * 功能：
 * - 任务入队/出队
 * - 任务优先级排序
 * - 任务超时管理
 * - 任务状态跟踪
 */
export class TaskQueueManager extends EventEmitter {
  private queue: Task[] = []
  private pendingTasks: Map<string, Task> = new Map()

  /**
   * 将任务加入队列（按优先级排序）
   */
  enqueue(task: Task): void {
    // 按优先级插入（优先级数字越小优先级越高）
    const insertIndex = this.queue.findIndex(t => t.priority > task.priority)
    if (insertIndex === -1) {
      this.queue.push(task)
    }
    else {
      this.queue.splice(insertIndex, 0, task)
    }

    getLoggerSafe().debug('任务入队', { taskId: task.id, priority: task.priority, queueLength: this.queue.length })
    this.emit('task:enqueued', task.id)
  }

  /**
   * 从队列中取出任务
   */
  dequeue(): Task | null {
    const task = this.queue.shift()
    if (task) {
      this.pendingTasks.set(task.id, task)
      this.startTimeout(task)
      getLoggerSafe().debug('任务出队', { taskId: task.id, pendingCount: this.pendingTasks.size })
      this.emit('task:dequeued', task.id)
    }
    return task || null
  }

  /**
   * 启动任务超时定时器
   */
  private startTimeout(task: Task): void {
    setTimeout(() => {
      if (this.pendingTasks.has(task.id)) {
        this.pendingTasks.delete(task.id)
        getLoggerSafe().warn('任务超时', { taskId: task.id, timeout: task.timeout })
        this.emit('task:timeout', task.id)
      }
    }, task.timeout)
  }

  /**
   * 标记任务完成
   */
  complete(taskId: string): void {
    this.pendingTasks.delete(taskId)
    getLoggerSafe().debug('任务完成', { taskId, pendingCount: this.pendingTasks.size })
    this.emit('task:completed', taskId)
  }

  /**
   * 标记任务失败
   */
  fail(taskId: string): void {
    this.pendingTasks.delete(taskId)
    getLoggerSafe().debug('任务失败', { taskId, pendingCount: this.pendingTasks.size })
    this.emit('task:failed', taskId)
  }

  /**
   * 获取队列长度
   */
  getQueueLength(): number {
    return this.queue.length
  }

  /**
   * 获取待处理任务数
   */
  getPendingCount(): number {
    return this.pendingTasks.size
  }

  /**
   * 获取队列统计信息
   */
  getStats(): {
    queueLength: number
    pendingCount: number
  } {
    return {
      queueLength: this.queue.length,
      pendingCount: this.pendingTasks.size,
    }
  }
}
